import time

# from MyWebServer import WebServer

# 设置静态文件根目录
HTML_ROOT_DIR = "./html"

class Application(object):
    """这是核心框架，是通用的"""
    def __init__(self,urls):
        # 设置路由信息
        self.urls = urls

    def __call__(self, env, start_response):
        path = env.get("PATH_INFO", "/")
        # 判断是否请求的是静态文件
        if path.startswith("/static"):
            # 要访问静态文件
            file_name = path[7:]

            # 打开文件,读取内容
            try:
                file = open(HTML_ROOT_DIR + file_name, "rb")
            except IOError:
                # 未找到路由信息，404错误
                starts = "404 Not Found"
                headers = []
                start_response(starts, headers)
                return "Not Found"
            else:
                file_data = file.read()
                file.close()

                # 未找到路由信息，404错误
                starts = "200 OK"
                headers = []
                start_response(starts, headers)
                return file_data.decode("utf_8")
        else:
            for url, handler in self.urls:
                if path == url:
                    return handler(env, start_response)
            # 未找到路由信息，404错误
            starts = "404 Not Found"
            headers = []
            start_response(starts, headers)
            return "Not Found"

def show_ctime(environ, start_response):
    status = "200 OK"

    headers = [
        ("Content-Type", "text/plain"),
    ]
    start_response(status, headers)

    # 返回响应体
    return ("Hello world from a simple WSGI application!--->%s\n" % time.ctime())

def say_hello(environ, start_response):
    status = "200 OK"

    headers = [
        ("Content-Type", "text/plain"),
    ]
    start_response(status, headers)

    # 返回响应体
    return "say_hello"

urls = [
        ("/ctime", show_ctime),
        ("/sayhello", say_hello),
    ]

app = Application(urls)

# if __name__ == '__main__':
#
#     urls = [
#         ("/ctime", show_ctime),
#         ("/sayhello", say_hello),
#     ]
#
#     app = Application(urls)
#     http_server = WebServer(app)
#     http_server.bind(8080)
#     http_server.start()
